#!/usr/bin/python3
"""
Create pam_limits module configuration.

This stage creates a pam_limits module configuration file with the given name in
/etc/security/limits.d. Provided list of configuration directives is written
as separate lines into the configuration file. At least one configuration
directive must be specified.
"""


import sys

import osbuild.api


SCHEMA = r"""
"definitions": {
  "configuration": {
    "type": "object",
    "additionalProperties": false,
    "required": ["domain", "type", "item", "value"],
    "description": "pam_limits module configuration directive representing one line in the configuration.",
    "properties": {
      "domain": {
        "type": "string",
        "description": "Domain to which the limit applies. E.g. username, groupname, etc."
      },
      "type": {
        "type": "string",
        "description": "Type of the limit.",
        "enum": ["hard", "soft", "-"]
      },
      "item": {
        "type": "string",
        "description": "The resource type, which is being limited.",
        "enum": [
          "core",
          "data",
          "fsize",
          "memlock",
          "nofile",
          "rss",
          "stack",
          "cpu",
          "nproc",
          "as",
          "maxlogins",
          "maxsyslogins",
          "nonewprivs",
          "priority",
          "locks",
          "sigpending",
          "msgqueue",
          "nice",
          "rtprio"
        ]
      },
      "value": {
        "oneOf": [
          {
            "type": "string",
            "enum": ["unlimited", "infinity"]
          },
          {
            "type": "integer"
          }
        ],
        "description": "The limit value."
      }
    }
  }
},
"additionalProperties": false,
"required": ["filename", "config"],
"properties": {
  "filename": {
    "type": "string",
    "description": "Name of the pam_limits module configuration file to create.",
    "pattern": "^[\\w.-]{1,250}\\.conf$"
  },
  "config": {
    "additionalProperties": false,
    "type": "array",
    "description": "List of configuration directives written into the configuration file.",
    "minItems": 1,
    "items": {
      "$ref": "#/definitions/configuration"
    }
  }
}
"""


def main(tree, options):
    filename = options["filename"]
    cfg = options["config"]

    limitsd_config_dir = f"{tree}/etc/security/limits.d"

    cfg_lines = []
    for cfg_item in cfg:
        cfg_line = f'{cfg_item["domain"]} {cfg_item["type"]} {cfg_item["item"]} {cfg_item["value"]}\n'
        cfg_lines.append(cfg_line)

    with open(f"{limitsd_config_dir}/{filename}", "w") as f:
        f.writelines(cfg_lines)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
